package com.yhy.manager.service;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yhy.manager.domain.AnalysisByDay;
import com.yhy.manager.domain.Log;
import com.yhy.manager.mapper.AnalysisByDayMapper;
import com.yhy.manager.mapper.LogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class LogService {

    @Autowired
    private LogMapper logMapper;

    @Autowired
    private AnalysisByDayMapper analysisByDayMapper;

    //保存登录日志
    public void save(Log log) {
        logMapper.insert(log);
    }

    public void analysis() throws ParseException {
//        1.获取当前日期
        String todayStr = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//        2.获取昨日日期 通过hutool工具包获取
        String yesterday = DateUtil.yesterday().toString("yyyy-MM-dd");
//        3.从tb_log表统计昨日注册 并存入tb_analysis_by_day表
        Integer numRegistered = logMapper.queryByTypeAndLogTime("0102", todayStr);
//        4.统计每日登录用户
        Integer numLogin = logMapper.queryByTypeAndLogTime("0101", todayStr);
//        5.统计活跃用户
        Integer numActive = logMapper.queryByLogTime(todayStr);
//        6.统计次日留存
        Integer numRetention1d = logMapper.queryNumRetention1d(todayStr, yesterday);
//        7.构造对象AnalysisByDay对象 保存到tb_analysis_by_day表里
//        7.1先从表里查看当前日期有没有统计过
        Date todayDate = new SimpleDateFormat("yyyy-MM-dd").parse(todayStr);
        QueryWrapper qw = new QueryWrapper();
        qw.eq("record_date",todayDate);
        AnalysisByDay analysisByDay = analysisByDayMapper.selectOne(qw);

        if(analysisByDay == null){
            //不存在 封装完整对象 保存
            analysisByDay = new AnalysisByDay();
            analysisByDay.setRecordDate(todayDate);
            analysisByDay.setNumRegistered(numRegistered);
            analysisByDay.setNumLogin(numLogin);
            analysisByDay.setNumActive(numActive);
            analysisByDay.setNumRegistered(numRetention1d);
            analysisByDay.setCreated(new Date());
            analysisByDay.setUpdated(new Date());
            analysisByDayMapper.insert(analysisByDay);
        }else{
            //存在 更新统计数据和更新时间
            analysisByDay.setNumRegistered(numRegistered);
            analysisByDay.setNumLogin(numLogin);
            analysisByDay.setNumActive(numActive);
            analysisByDay.setNumRetention1d(numRetention1d);
            analysisByDayMapper.updateById(analysisByDay);
        }
    }
}
